"""Logistic算法原理推导：https://blog.csdn.net/kaka19880812/article/details/46993917

array()的乘法是矩阵中对应位置的两个数相乘。
mat()的乘法是矩阵乘法。
array经过split后数据会变成str格式，后面使用的时候一定不要忘记转换回去
"""

import matplotlib.pyplot as plt
import numpy as np
import random

def loadDataSet():
    dataMat = []
    labelMat = []
    f = open("testSet.txt")
    for line in f.readlines():
        # strip()的用法是移除字符串头尾指定的字符序列。
        # 返回移除字符串头尾指定的字符生成的新字符串
        lineArr = line.strip().split()
        dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])]) # 文件的前两列为X1,X2,第三列为类别标签，1.0表示设置的偏差
        labelMat.append(int(lineArr[2]))
    return dataMat, labelMat


def sigmoid(inX):
    return 1.0 / (1 + np.exp(-inX)) # 注意，此时的exp只能为numpy的类型，不能为普通数值的math类型，否则会出错


# 梯度上升算法
def gradAscent(dataMatIn, classLabels):
    """
     mat与array的区别之一就是mat中的*是矩阵乘法，而array的乘法是矩阵中对应的元素相乘
    """
    dataMatrix = np.mat(dataMatIn) # 100*3 注意mat类型的数据
    labelMat = np.mat(classLabels).transpose() # 将行向量转置为列向量
    m, n = np.shape(dataMatrix)  # m->数据量，样本数 n->特征数
    alpha = 0.001 # 步长
    maxCycles = 500 # 最大迭代次数
    weights = np.ones((n, 1)) # ones函数创建n*1的矩阵(3*1)，其元素值均为1
    for k in range(maxCycles):
        h = sigmoid(dataMatrix * weights) # h为100*1
        error = labelMat - h  # label相当于原来的数据，h为预测的数据
        weights = weights + alpha * dataMatrix.transpose() * error
    return weights


# 随机梯度上升算法
def stocGradAscent0(dataArr, classbels, numIter):    #书上的命名容易误导人，改一下
    m, n = np.shape(dataArr)
    alpha = 0.01
    weights = np.ones(n)
    for j in range(numIter):
        for i in range(m):
            h = sigmoid(sum(dataArr[i] * weights))  #数值
            error = classbels[i] - h    #数值
            weights = weights + alpha * error * dataArr[i]
    return weights


# 改进的随机梯度上升算法
def stocGradAscent1(dataMatrix, classLabels, numIter):
    m, n = np.shape(dataMatrix)
    weights = np.ones(n)
    for j in range(numIter):
        dataIndex = range(m)
        for i in range(m):
            alpha = 4 / (1.0 + j + i) + 0.01
            randIndex = int(random.uniform(0, len(dataMatrix)))
            h = sigmoid(sum(dataMatrix[randIndex] * weights))
            error = classLabels[randIndex] - h
            weights = weights + alpha * error * dataMatrix[randIndex]
            del(list(dataIndex)[randIndex]) # 注意要将dataIndex变为list类型
    return weights


# 可视化处理
def plotBestFit(weights):
    dataMat, labelMat = loadDataSet()
    dataArr = np.array(dataMat) #numpy的matrix类型转化成array
    n = np.shape(dataArr)[0] # n为样本数
    xcord1 = []
    ycord1 = [] # 类别为1的样本的x,y坐标
    xcord2 = []
    ycord2 = [] # 类别为0的样本的x,y坐标
    for i in range(n):
        if int(labelMat[i]) == 1:
            xcord1.append(dataArr[i, 1])
            ycord1.append(dataArr[i, 2])
        else:
            xcord2.append(dataArr[i, 1])
            ycord2.append(dataArr[i, 2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcord1, ycord1, s=30, c="red", marker="s") # s参数是数据点的粗细，marker是标记（'s'是正方形，默认圆形）
    ax.scatter(xcord2, ycord2, s=30, c="green")
    x = np.arange(-3.0, 3.0, 0.1)  # 直线x坐标的取值范围
    y = (-weights[0] - weights[1] * x) / weights[2]  # 直线方程
    ax.plot(x, y)
    plt.xlabel('X1')
    plt.ylabel('X2')
    plt.show()


def main():
    dataMat, labelMat = loadDataSet()
    weights = gradAscent(dataMat, labelMat)
    print(weights)
    weights1 = stocGradAscent0(np.array(dataMat), labelMat, 200)
    print(weights1)
    plotBestFit(weights.getA())  #getA()函数将Numpy.matrix型转为ndarray型
    plotBestFit(weights1)
    weights2 = stocGradAscent1(np.array(dataMat), labelMat, 200)
    print(weights2)
    plotBestFit(weights1)


if __name__ == '__main__':
    main()